//
//  HomeView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/6.
//

import SwiftUI
import TLCLock

struct MainView: View {
    
    var body: some View {
        Group {
            HomeView()
        }
    }
}

struct HomeView: View {
    @State var title: String = "设备列表"
    @State var deviceList: [ScanDevice] = []
    
    var body: some View {
        NavigationView {
            VStack {
                HStack(alignment: /*@START_MENU_TOKEN@*/ .center /*@END_MENU_TOKEN@*/, spacing: 10) {
                    Button(
                        action: onTapScan,
                        label: {
                            Text("开始扫描").font(.body)
                                .padding(.horizontal)
                                .frame(maxWidth: .infinity)
                        }
                    )
                    Button(
                        action: onTapStop,
                        label: {
                            Text("停止扫描").font(.body)
                                .padding(.horizontal)
                                .frame(maxWidth: .infinity)
                        }
                    )
                    NavigationLink(destination: {
                        DetailView(mac: Server.testMac)
                    }) {
                        Text("Test")
                            .padding(.horizontal)
                            .frame(maxWidth: .infinity)
                    }
                }
                .frame(height: 44)
                .padding(.horizontal, 16)
                .background(Color(UIColor.systemBackground))
                List {
                    ForEach(deviceList) { item in
                        NavigationLink(destination: {
                            return DetailView(mac: item.mac)
                        }) {
                            HStack(alignment: .top, spacing: 6) {
                                VStack(alignment: .leading, spacing: 4) {
                                    HStack {
                                        Text(item.name ?? "UNKNOWN")
                                            .lineLimit(1)
                                            .truncationMode(.tail)
                                        Spacer()
                                        Text("rssi: \(item.RSSI)")
                                            .frame(maxWidth: 70, alignment: .trailing)
                                    }
                                    Text(item.mac)
                                        .lineLimit(1)
                                        .truncationMode(.tail)
                                    Text(item.identifier)
                                        .font(.system(size: 12))
                                        .lineLimit(1)
                                        .truncationMode(.tail)
                                    Text("isScreenOn: \(item.isScreenOn)  isAddState: \(item.isAddState)  isDfuState: \(item.isDfuState)")
                                        .font(.system(size: 12))
                                        .lineLimit(1)
                                        .truncationMode(.tail)
                                }
                            }
                        }
                    }
                }
            }.navigationTitle(Text(title))
                .navigationBarItems(
                    leading: Button(
                        action: checkIsSupport,
                        label: {
                            Text("蓝牙状态")
                        }
                    ),
                    trailing: HStack {
                        NavigationLink(destination: SettingView()) {
                            Text("设置").font(.body)
                        }
                    }
                ).navigationBarTitleDisplayMode(.inline)
                .onDisappear {
                    onTapStop()
                }
        }
    }
    
    func checkIsSupport() {
        Task {
            let state = await TLCManager.asyncBlueState()
            
            if state == .poweredOn {
                showToast("当前蓝牙可用")
            } else {
                showToast("当前蓝牙不可用：\(state)")
            }
        }
    }
    
    func onTapScan() {
        deviceList.removeAll()
        TLCManager.startScan(featureCode: Server.testFeatureCode) { result in
            switch result {
            case .scanStarted:
                title = "搜索中"
                Log.info("已开始扫描")
            case let .scanResult(device):
                deviceList.removeAll { $0.mac == device.mac }
                deviceList.append(device)
            case let .scanStopped(error):
                title = "设备列表"
                if let e = error {
                    
                    if case .blueState(let state) = e {
                        Log.error("扫描失败： \(state)")
                    }
                    
                    showToast(e.localizedDescription)
                } else {
                    Log.info("已停止扫描")
                }
            }
        }
    }
    
    func onTapStop() {
        TLCManager.stopScan()
    }
}
